package com.gitee.urick.union.api.union.handler.v1;


import com.gitee.urick.union.api.union.IHandler;
import com.gitee.urick.union.utils.TipsCode;
import com.gitee.urick.union.api.union.dto.ReqCtx;
import com.gitee.urick.union.api.union.dto.base.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 修改记录
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 修改日期				修改者						备注信息
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 2020年08月25日			kkroc							初始化版本
 */
@Slf4j
@Component("dispatcher_v1")
public class DispatcherV1 implements IHandler {
    @Autowired
    private ApplicationContext appCtx;

    @Override
    public void beforeHandle(ReqCtx ctx) {
    }

    @Override
    public void handle(ReqCtx ctx) {
        String handlerName = String.join("_", ctx.getAction(), "request");
        if (!appCtx.containsBean(handlerName)) {
            ctx.setRes(new BaseRes().error("不支持的请求类型：" + ctx.getAction()));
        } else {
            IHandler handler = appCtx.getBean(handlerName, IHandler.class);
            try {
                handler.beforeHandle(ctx);
            } catch (Exception e) {
                log.error("初始化Handler:{}异常", handlerName, e);
                ctx.makeTips(TipsCode.System_Error);
            }
            if (!(ctx.isHandled() || ctx.isTerminated())) {
                try {
                    handler.handle(ctx);
                } catch (Exception e) {
                    log.error("Handler:{} 业务处理异常", handlerName, e);
                    ctx.makeTips(TipsCode.System_Error);
                }
            }
        }
    }

    @Override
    public void afterHandle(ReqCtx ctx) throws Exception {

    }
}
